﻿using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
using YJKGridTopologyCal.Geometries;
using YJKGridTopologyCal.Index.Strtree;

namespace YJKGridTopologyCal.Operation.Distance
{
	public static class FacetSequenceTreeBuilder
	{
		public static STRtree<FacetSequence> BuildSTRtree(IGeometry g)
		{
			STRtree<FacetSequence> strtree = new STRtree<FacetSequence>(4);
			foreach (FacetSequence facetSequence in FacetSequenceTreeBuilder.ComputeFacetSequences(g))
			{
				strtree.Insert(facetSequence.Envelope, facetSequence);
			}
			strtree.Build();
			return strtree;
		}

		private static List<FacetSequence> ComputeFacetSequences(IGeometry g)
		{
			List<FacetSequence> sections = new List<FacetSequence>();
			g.Apply(new GeometryComponentFilter(delegate(IGeometry geom)
			{
				if (geom is ILineString)
				{
					FacetSequenceTreeBuilder.AddFacetSequences(((ILineString)geom).CoordinateSequence, sections);
					return;
				}
				if (geom is IPoint)
				{
					FacetSequenceTreeBuilder.AddFacetSequences(((IPoint)geom).CoordinateSequence, sections);
				}
			}));
			return sections;
		}

		private static void AddFacetSequences(ICoordinateSequence pts, List<FacetSequence> sections)
		{
			int i = 0;
			int count = pts.Count;
			while (i <= count - 1)
			{
				int num = i + 6 + 1;
				if (num >= count - 1)
				{
					num = count;
				}
				FacetSequence item = new FacetSequence(pts, i, num);
				sections.Add(item);
				i += 6;
			}
		}

		private const int FacetSequenceSize = 6;

		private const int STRtreeNodeCapacity = 4;
	}
}
